package main

import (
	"fmt"

	"log/slog"
	"net/http"
	"os"

	"torrent/config"
	"torrent/database/postgressql"
	"torrent/haders"

	"github.com/alexedwards/scs/v2"
)

const (
	envLocal = "local"
	envDev   = "dev"
	envProd  = "prod"
)

func main() {
	cfg := config.MustLoad()
	log := setupLogger(cfg.Env)
	pool, err := postgressql.NewPool(cfg.StoragePath)
	if err != nil {
		log.Error("error connected DB", err)
		return
	}

	session := scs.New()
	defer pool.PgPool.Close()

	server := &http.Server{
		Addr:    fmt.Sprint(cfg.Address),
		Handler: session.LoadAndSave(haders.NewRouter(pool, session, log)),
	}

	log.Info("Starting HTTP Server. ", slog.String("Listening at ", server.Addr))

	if err := server.ListenAndServe(); err != http.ErrServerClosed {
		log.Warn("%v", err)
	} else {
		log.Info("Server closed!")
	}
}

func setupLogger(env string) *slog.Logger {
	var log *slog.Logger

	switch env {
	case envLocal:
		log = slog.New(
			slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug}),
		)
	case envDev:
		log = slog.New(
			slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}),
		)
	case envProd:
		log = slog.New(
			slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}),
		)
	default: // If env config is invalid, set prod settings by default due to security
		log = slog.New(
			slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}),
		)
	}

	return log
}
